package com.book.activeMQ.consumers;

import com.book.activeMQ.send.SendMessage;
import com.book.dto.BookDto;
import com.book.dto.OrderDetailDto;
import com.book.dto.UserDto;
import com.book.pojo.OrderBook;
import com.book.pojo.User;
import com.book.service.BookService;
import com.book.service.OrderService;
import com.book.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author Jincheng.Li
 * @Date 2021/6/4 9:02 下午
 * @Project_Name graduation-project
 */
@Component
@Slf4j
public class SendMailMQ implements MessageListener {
    @Autowired
    private SendMessage sendMessage;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private BookService bookService;
    @Override
    public void onMessage(Message message) {
        try {
            String orderNo = ((TextMessage) message).getText();
            log.info("SendMailMQ#toEmial:{}",orderNo);
            OrderBook orderBook = orderService.getOrderByNo(orderNo);
            if (orderBook == null){
                return;
            }
            String uCode = orderBook.getUCode();
            User userByCode = userService.getUserByCode(uCode);
            List<OrderDetailDto> orderDetailByOrderNo = orderService.getOrderDetailByOrderNo(orderNo);
            List<String> bookCodeList = orderDetailByOrderNo.stream().map(OrderDetailDto::getUbCode).collect(Collectors.toList());
            List<BookDto> bookListByBookCode = bookService.getBookListByBookCode(bookCodeList);
            Map<Integer,List<BookDto>> map = bookListByBookCode.stream().collect(Collectors.groupingBy(BookDto::getUId));
            for (Integer key:map.keySet()
                 ) {
                List<BookDto> bookDtos = map.get(key);
                UserDto userById = userService.getUserById(key);
                String targetMail = userById.getUEmail();
                StringBuffer sb = new StringBuffer();
                sb.append("你在二手书交易网站发布的图书被用户 ").append(userByCode.getUName()).append(" 下单购买了\n");
                sb.append("购买列表：\n");
                bookDtos.forEach(m->{
                    sb.append(m.getBookTitle()).append("\n");
                });
                sendMessage.sendMailCode("二手书交易网站交易信息",targetMail,sb.toString());
            }
        }catch (Exception e){
            return;
        }
    }
}
